const Koa = require('koa');
const http = require('http');
const app = new Koa();
const router = require('koa-router')();
const co = require('co');
const convert = require('koa-convert');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser')();
const logger = require('koa-logger');
const session = require('koa-session');
const db = require('./src/models/db');
const koaBody = require('koa-body');
const schedule = require('node-schedule');

const rule = new schedule.RecurrenceRule();
import {frontendRouter,serverRouter} from './src/router';
onerror(app);
// cookies
app.keys = ['eycms:secret'];
const CONFIG = {
  key: 'eycms', 
  maxAge: 604800000,  // 7天
  overwrite: true, 
  signed: true, 
};
app.use(convert(logger()))
   .use(convert(session(CONFIG,app)))
   .use(convert(require('koa-static')(__dirname + '/public')));
app.use(koaBody({
  formLimit: 1048576,  // 最大1M
  textLimit: 1048576}))

app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
// router
app.use(require('./src/middleware/response'));
app.use(require('./src/middleware/response'));
app.use(require('./src/middleware/filter'));
app.use(serverRouter.routes())
	.use(serverRouter.allowedMethods())
  .use(frontendRouter.routes())
  .use(frontendRouter.allowedMethods());
// response
app.on('error', function(err, ctx){
  logger.error('server error', err, ctx);
  ctx.render('error', { message: ' 服务器错误!',error: err });
});

rule.minute = [0, 1];
// var j = schedule.scheduleJob(rule, function(){  
//     console.log('执行一下')
// });
module.exports = app;